<template>
  <el-container>
    <header></header>
    <el-main>
      <img src="@/assets/logo.png"/>
      <br/>
      <el-input class="input_style" type="text" v-model="loginInfo.username" placeholder="用户名"> </el-input>
      <br/>
      <el-input class="input_style" type="password" v-model="loginInfo.password" placeholder="密码"> </el-input>
      <br/>
      <el-button class="login_style" type="primary" v-on:click="login">登录</el-button>
      <br/>
      <el-checkbox :aria-selected="keep" onclick="keepAccount"> 是否保存账户信息 </el-checkbox>
    </el-main>
  </el-container>
</template>

<script>

import Header from '../common/Header'

export default {
  name: 'Login',
  components: {Header},
  data () {
    return {
      responseResult: {
        code: 0,
        data: '',
        msg: ''
      }
    }
  },
  computed: {
    keep: this.$store.keepAccount,
    loginInfo: this.$store.getLastLoginInfo()
  },
  methods: {
    login () {
      console.log('登录')
      this.$axios.post('/login', {
        username: this.loginInfo.username,
        password: this.loginInfo.password
      })
        .then(response => {
          this.loginInfo = JSON.stringify(response.data)
          this.responseResult = response.data
          // eslint-disable-next-line eqeqeq
          if (this.responseResult.code === 10) {
            this.updateToken(this.responseResult.data)
            if (this.keep) {
              this.saveLoginInfo()
            }
            this.$router.replace({path: '/index'})
          } else {
            this.$message.error(this.responseResult.msg)
          }
        }).catch(error => {
          this.$message.error('您的网络有些问题哦，请稍后尝试!')
          console.log(error)
          this.$router.replace({path: '/index'})
        })
    },
    keepAccount () {
      this.$store.dispatch('keepAccount')
    },
    updateToken (token) {
      this.$store.dispatch('setToken', token)
    },
    saveLoginInfo () {
      this.$store.dispatch('saveLoginInfo', this.loginInfo)
    }
  }
}
</script>

<style scoped>
  .login{
    margin-top: 20px;
  }
  .input_style{
    width: 300px;
    margin-bottom: 10px;
  }
  .login_style{
    width: 300px;
  }
 </style>
